package com.gitee.wsl.struct.generator.sample

import com.gitee.wsl.time.toLocalDateTime
import kotlin.random.Random
import kotlin.test.Test
import kotlin.test.assertEquals
import kotlin.test.assertFalse
import kotlin.test.assertTrue


/**
 * 16位数字卡号生成器单元测试用例
 *
 * @author liuzhaoming
 * @date 2017/11/22
 * @see CardIdGenerator
 */
class CardIdGeneratorTest {
    private val cardIdGenerator: CardIdGenerator = CardIdGenerator()

    @Test
    fun generate() {
        val id: Long = cardIdGenerator.generate()
        assertEquals(16, id.toString().length)
    }

    @Test
    fun validate() {
        var id: Long = cardIdGenerator.generate()
        assertTrue(cardIdGenerator.validate(id))
        assertFalse(cardIdGenerator.validate(++id))
    }

    @Test
    fun parse() {
        val id: Long = cardIdGenerator.generate()
        val results = cardIdGenerator.parse(id)!!
        assertEquals(1L, results[0])
        assertEquals(1L, results[2])
        assertEquals(0L, results[3])

        println("System: " + results[0])
        val timestamp = results[1]
        val dateTime = timestamp.toLocalDateTime()
        println("Time: $dateTime")
        println("Machine id: " + results[2])
        println("Sequence: " + results[3])
    }

    @Test
    fun performance() {
        val num: Long = 100
        for (i in 0 until num) {
            val id: Long = cardIdGenerator.generate()
            println(id)
        }
    }

    @Test
    fun crash() {
        val num: Long = 10000000
        var passNum: Long = 0

        for (i in 0 until num) {
            val sb: StringBuilder = StringBuilder()
            for (j in 0..15) {
                sb.append(Random.nextInt(100) / 10)
            }

            val id: Long = sb.toString().toLong()
            if (cardIdGenerator.validate(id)) {
                passNum++
            }
        }

        println(passNum)
    }

    @Test
    fun crash1() {
        val num: Long = 1000000
        var passNum: Long = 0
        var id: Long = cardIdGenerator.generate()
        for (i in 0 until num) {
            if (cardIdGenerator.validate(++id)) {
                passNum++
            }
        }

        println(passNum)
    }
}
